﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Net;


namespace ConsoleTranAccountData
{
	class Program
	{
		
		static void Main(string[] args)
		{
			try
			{
				DO.Common.Trace.SetLogFile(DO.Common.DreamOnConfig.logFolder, "TranAccountData");
				DateTime startDate;
				DateTime endDate = DateTime.Today;
				string lastMoney = "0";
				if (args.Length != 0)
				{
					endDate = DateTime.Parse(args[0]);
				}

				using (DO.Common.DataFunction df = new DO.Common.DataFunction(DO.Common.DreamOnConfig.connectionString_web))
				{
					
					#region ===========取得開始日及最後總額

					string SQL = "SELECT TOP 1 DATEADD(d, 1, ASSET_DATE), ASSET_MONEY FROM ASSET ORDER BY ASSET_DATE DESC";
					System.Data.DataSet ds = new System.Data.DataSet();
					if (df.RunSqlCommand(SQL, out ds))
					{
						startDate = DateTime.Parse(ds.Tables[0].Rows[0][0].ToString());
						lastMoney = ds.Tables[0].Rows[0]["ASSET_MONEY"].ToString();
						DO.Common.Trace.DebugWrite("TranAccountData", "startDate=" + startDate.ToString("yyyyMMdd"));
					}
					else
					{
						DO.Common.Trace.InfoWrite("TranAccountData", "取得startDate失敗!");
						return;
					}

					DO.Common.Trace.DebugWrite("TranAccountData", "endDate=" + endDate.ToString("yyyyMMdd"));

					#endregion


					//從遠端取得帳單
					getRemoteAsset.getAssetHtml(startDate, endDate);

					#region ===========待user刪除不需要的檔案
					Console.WriteLine("Press 'y' to continue, 'n' to cancel !");
					while (true)
					{
						char choice = Console.ReadKey().KeyChar;
						if (choice.Equals('y'))
						{
							break;
						}
						else if (choice.Equals('n'))
						{
							DO.Common.Trace.InfoWrite("TranAccountData", "user cancel!");
							return;
						}
					}
					#endregion

					//parse帳單內容產出sql字串
					SQL = DataToSQL(lastMoney);
					DO.Common.Trace.InfoWrite("TranAccountData", SQL);

					df.RunSqlCommand(SQL);
				}
			}
			catch (Exception ex)
			{
				DO.Common.Trace.ErrorWrite("TranAccountData", ex.ToString());
				System.Console.WriteLine(ex.ToString());
			}
		}

		


		private static string DataToSQL(string lastMoney)
		{
			string Sqlstr = "";
			string path = DO.Common.DreamOnConfig.getXmlNodeInnerText("config.xml", "ConsoleTranAccountData/accountDataFolder");
			
			try
			{
				string regexStr_asset = @"權益總值\s+(\d+)";//DO.Common.DreamOnConfig.getXmlNodeInnerText("config.xml", "ConsoleTranAccountData/regex_asset");
				DO.Common.Trace.InfoWrite("DataToSQL", "regex_asset=" + regexStr_asset);
				
				string regexStr_date = @"(\d+-\d+-\d+)&nbsp;&nbsp;買賣報告書-&nbsp";//DO.Common.DreamOnConfig.getXmlNodeInnerText("config.xml", "ConsoleTranAccountData/regex_date");
				DO.Common.Trace.InfoWrite("DataToSQL", "regex_date=" + regexStr_date);
				
				Regex regex_asset = new Regex(regexStr_asset, RegexOptions.IgnoreCase);
				Regex regex_date = new Regex(regexStr_date, RegexOptions.IgnoreCase);

				string[] strFiles = Directory.GetFiles(path, "*.*");
				string asset = lastMoney;
				foreach (string name in strFiles)
				{
					using (StreamReader sr = new StreamReader(name, System.Text.Encoding.Default))
					{
						string file = sr.ReadToEnd();
						Match ma = regex_asset.Match(file);
						if (ma.Success)
							asset = ma.Groups[1].ToString();

						ma = regex_date.Match(file);
						string date = ma.Groups[1].ToString();

						Sqlstr += "insert into [Asset] ( [ASSET_DATE] , [ASSET_MONEY] ) values('" + date + "'," + asset + ");";
					}
				}

			}
			catch (Exception ex)
			{
				DO.Common.Trace.ErrorWrite("DataToSQL", ex.ToString());
				Sqlstr = "";
			}
			return Sqlstr;
		}
	}
}
